﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using GraphosData;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Windows.Data;

namespace GraphosControls
{
	public class VisualNode : Button
	{
		public VisualNode(Node node, Canvas parent)
		{
			DataContext = this;
			m_node = node;
			m_parentCanvas = parent;

			m_parentCanvas.Children.Add(this);

			Canvas.SetLeft(this, m_parentCanvas.ActualWidth / 2);
			Canvas.SetTop(this, m_parentCanvas.ActualHeight / 2);
		}

		public bool IsSelected
		{
			get { return (bool)GetValue(IsSelectedProperty); }
			set { SetValue(IsSelectedProperty, value); }
		}
		public static readonly DependencyProperty IsSelectedProperty =
			 DependencyProperty.Register("IsSelected", typeof(bool), typeof(VisualNode), new UIPropertyMetadata(false));

		public Point Location
		{
			get { return (Point)GetValue(LocationProperty); }
			set { SetValue(LocationProperty, value); }
		}
		public static readonly DependencyProperty LocationProperty =
			 DependencyProperty.Register("Location", typeof(Point), typeof(VisualNode), new UIPropertyMetadata(new Point(0, 0), new PropertyChangedCallback(OnLocationChanged)));
		private static void OnLocationChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
		{
			VisualNode node = sender as VisualNode;
			Canvas.SetLeft(node, node.Location.X - node.m_center.X);
			Canvas.SetTop(node, node.Location.Y - node.m_center.Y);
		}

		public Node Node
		{
			get { return m_node; }
		}

		public IEnumerable<VisualNode> AdjacentVisualNodes { get; set; }

		public void DestroyWithAnimation()
		{
			BeginAnimation(OpacityProperty, m_opacityAnim);
			m_destroyTimer.Tick += new EventHandler(DestroyTimer_Tick);
			m_destroyTimer.IsEnabled = true;
		}

		void DestroyTimer_Tick(object sender, EventArgs e)
		{
			m_destroyTimer.IsEnabled = false;
			m_destroyTimer.Tick -= DestroyTimer_Tick;
			m_parentCanvas.Children.Remove(this);
		}
		protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
		{
			base.OnRenderSizeChanged(sizeInfo);
			m_center = new Point(sizeInfo.NewSize.Width / 2, sizeInfo.NewSize.Height / 2);
		}
		protected override void OnInitialized(EventArgs e)
		{
			Style = (Style)TryFindResource("VisualNodeStyle");
			base.OnInitialized(e);
		}
		private Node m_node;
		private Canvas m_parentCanvas;
		private Point m_center = new Point(0, 0);

		private DoubleAnimation m_opacityAnim = new DoubleAnimation() { To = 0.0, Duration = new Duration(TimeSpan.FromSeconds(Const.NodeDestroyAnimationTime)) };

		private DispatcherTimer m_destroyTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(Const.DestoryTime) };
	}
}
